<template>
  <div class="topic">
    <el-form ref="form" :rules="rules" :model="params" label-width="80px">
      <el-form-item label="专题名称" prop="topicName">
        <el-input v-model="params.topicName" class="width" placeholder="请输入专题名称" maxlength="30"></el-input>
        <span class="confirm">您还可以输入{{30-params.topicName.length}}个字</span>
      </el-form-item>
      <el-form-item label="主讲人" prop="lecturer">
        <el-input v-model="params.lecturer" class="width" placeholder="请输入内容作者"></el-input>
      </el-form-item>
      <el-form-item label="权重" prop="sort">
        <el-input-number v-model="params.sort" :min="0" label="描述文字" class="width"></el-input-number>
      </el-form-item>
      <el-form-item label="专题封图" prop="cover" class="unique">
        <el-upload
          :headers="headers"
          action="/tools/oss/upload"
          :on-success="uploadSuccess"
          :show-file-list="false"
          :file-list="fileList"
          :auto-upload="true"
          :accept="'.jpg,.png'"
        >
          <el-form-item class="imgBox" v-if="params.cover">
            <img :src="params.cover" :alt="params.cover">
          </el-form-item>
          <el-button size="small" type="primary">上传图片</el-button>
          <div slot="tip" class="el-upload__tip">
            <p>注：只能上传 jpg/png 文件，且仅单张，建议尺寸 像素 750*440</p>
            <p>色彩建议 不支持白色图片，尽量保证颜色铺满</p>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="专题课程" prop="commodities">
        <el-button type="primary" size="small" @click="choiceCourse">选择课程</el-button>
        <el-button
          v-if="choiceCourseList[this.params.type].length>0"
          size="mini"
          type="primary"
          @click="deleteAllLesson"
        >重置</el-button>
        <el-checkbox-group v-model="params.commodities" style="display:none"></el-checkbox-group>
        <!-- <div v-if="choiceCourseList.length>0">
          <el-tag
            v-for="(tag, index) in choiceCourseList"
            :key="tag.id"
            type="info"
            closable
            @close="deleteCourse(index)"
            style="margin-right:5px"
            :draggable="true"
            @drop="drop"
            @dragover="dragover"
          >
            {{tag.commodityName}}
          </el-tag>
        </div> -->
        <ul class="tag_list" v-if="choiceCourseList[this.params.type].length>0">
          <li
            class="tag_item"
            v-for="(tag, index) in choiceCourseList[this.params.type]"
            :key="tag.id"
            :data-index="index"
            :draggable="true"
            @drop="drop"
            @dragover.prevent
            @dragstart="dragstart"
            @dragend="dragend($event, tag)"
          >
            {{tag.commodityName}}
            <i class="tag_close" @click="deleteCourse(index)"></i>
          </li>
        </ul>
      </el-form-item>
      <el-form-item label="精品推荐" prop="recommend">
        <el-radio v-model="params.recommend" :label="true">是</el-radio>
        <el-radio v-model="params.recommend" :label="false">否</el-radio>
      </el-form-item>
      <el-form-item label="专题类型" prop="type" @change="handTypeChange">
        <el-radio v-model="params.type" :label="1">图文</el-radio>
        <el-radio v-model="params.type" :label="2">视频</el-radio>
        <el-radio v-model="params.type" :label="3">其他</el-radio>
      </el-form-item>
      <el-form-item label="简介" prop="summary">
        <el-input
          v-model="params.summary"
          type="textarea"
          class="bigInput"
          placeholder="请输入简介"
          :rows="5"
          maxlength="100"
        ></el-input>
        <span class="confirm">您还可以输入{{100-params.summary.length}}个字</span>
      </el-form-item>
      <el-form-item>
        <el-button v-if="shadow==false" @click="isShow">取消</el-button>
        <el-button type="primary" @click="operate">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="选择商品" :visible.sync="showDialog" :center="true" :modal="shadow">
      <div class="filter">
        <span class="label">年级：</span>
        <el-select
          v-model="filterParams.gradeId"
          size="small"
          placeholder="请选择"
          class="inputWidth"
          clearable
        >
          <el-option
            v-for="item in gradeList"
            :key="item.id"
            :label="item.gradeName"
            :value="item.id"
          ></el-option>
        </el-select>
        <span class="label" style="padding-left:10px;display:inline-black">科目：</span>
        <el-select
          v-model="filterParams.subjectId"
          size="small"
          placeholder="请选择"
          class="inputWidth"
          clearable
        >
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="item.subjectName"
            :value="item.id"
          ></el-option>
        </el-select>
        <span class="label" style="padding-left:10px;display:inline-black">名称：</span>
        <el-input
          v-model="filterParams.commodityName"
          placeholder="请输入商品名称"
          size="small"
          class="inputWidth"
        ></el-input>
        <el-button type="primary" size="small" @click="search">查询</el-button>
      </div>
      <el-table
        :data="courseList"
        v-loading="tableLoading"
        element-loading-text="数据加载中，请稍后"
        border
        fit
        highlight-current-row
        @select="handleSelectionChange"
        ref="multipleTable"
        @select-all="choiceAll"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="商品名称" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.commodityName}}</template>
        </el-table-column>
        <el-table-column label="科目">
          <template slot-scope="scope">{{scope.row.subjectName}}</template>
        </el-table-column>
        <el-table-column label="年级">
          <template slot-scope="scope">{{scope.row.gradeName}}</template>
        </el-table-column>
        <el-table-column label="权重">
          <template slot-scope="scope">{{scope.row.weights}}</template>
        </el-table-column>
      </el-table>
      <div v-show="!tableLoading" class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="filterParams.pageNo"
          :page-sizes="[10,20,30,50]"
          :page-size="filterParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <div class="botttomBut">
        <el-button type="success" icon="el-icon-success" size="small" @click="confirmCourse">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth' // 验权
import { rules, defaultParams } from './params.js'
import {
  commodityList,
  getGradeList,
  getSubjectList,
  addTopic,
  topicAmend
} from '@/api/topic'
export default {
  props: {
    addParams: {},
    shadow: Boolean
  },
  data() {
    return {
      rules,
      headers: {},
      fileList: [],
      params: { ...defaultParams },
      courseList: [],
      filterParams: {
        pageNo: 1,
        pageSize: 10,
        subjectId: null,
        gradeId: null,
        commodityType: null,
        commodityName: null
      },
      showDialog: false,
      tableLoading: false,
      choiceCourseList: {
        1: [],
        2: [],
        3: []
      },
      gradeList: [],
      subjectList: [],
      total: null,
      choiceTable: [],
      selectList: {
        1: [],
        2: [],
        3: []
      },
      targetIndex: 0,
      startIndex: 0
    }
  },
  watch: {
    addParams(params) {
      this.params = { ...this.params, ...params }
      if (this.params.commodities.length > 0) {
        this.choiceCourseList[this.params.type] = this.params.commodities
        this.selectList[this.params.type] = this.params.commodities
      } else {
        this.choiceCourseList[this.params.type] = []
      }
    }
  },
  created() {
    this.headers = { accessToken: getToken() }
    this.params = { ...defaultParams, ...this.addParams }
    if (this.params.commodities.length > 0) {
      this.choiceCourseList[this.params.type] = this.params.commodities
      this.selectList[this.params.type] = this.params.commodities
    }
    this.getGradeList()
    this.getSubjectList()
  },
  methods: {
    // 图片拖拽
    drop(event) {
      console.log('drop', event)
      this.targetIndex = parseInt(event.target.dataset.index)
      console.log('目标位置', this.targetIndex)
    },
    dragover(event) {
      event.preventDefault()
    },
    dragstart(event) {
      console.log('dragstart', event)
      this.startIndex = parseInt(event.target.dataset.index)
      console.log('起始位置', this.startIndex)
    },
    dragend(event, item) {
      event.dataTransfer.clearData()
      this.choiceCourseList[this.params.type].splice(this.startIndex, 1)
      this.choiceCourseList[this.params.type].splice(this.targetIndex, 0, item)
    },

    //上传图片成功
    uploadSuccess(response, file, fileList) {
      const {
        code,
        data: { picUrlList },
        message
      } = response
      if (code == 0) {
        this.fileList = [{ name: picUrlList[0], url: picUrlList[0] }]
        this.$set(this.params, 'cover', picUrlList[0])
        this.$refs.form.validate(valid => {})
      } else {
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '上传失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    //商品列表
    topicList() {
      this.tableLoading = true
      this.courseList = []
      commodityList(this.filterParams)
        .then(response => {
          const { code, data } = response
          if (code == 0) {
            this.tableLoading = false
            this.courseList = data.list
            this.total = data.total
            for (const i in data.list) {
              this.courseList[i]['pageNum'] = data.pageNum
            }
            this.$nextTick(() => {
              this.toggleSelection()
            })
          } else {
            this.tableLoading = false
          }
        })
        .catch(err => {
          this.tableLoading = false
        })
    },
    //选择课程
    choiceCourse() {
      this.showDialog = true
      this.filterParams.subjectId = null
      this.filterParams.commodityName = null
      this.filterParams.gradeId = null
      const map = {
        1 : 1,
        2: 2
      }
      this.filterParams.commodityType = map[this.params.type]
      this.topicList()
    },
    //年级列表
    getGradeList() {
      getGradeList().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.gradeList = data
        }
      })
    },
    //年级列表
    getSubjectList() {
      getSubjectList().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.subjectList = data
        }
      })
    },
    //表格搜素
    search() {
      this.filterParams.pageNo = 1
      this.topicList()
    },
    // 多少条一页
    handleSizeChange(val) {
      this.filterParams.pageSize = val
      this.topicList()
    },
    // 分页
    handleCurrentChange(val) {
      this.filterParams.pageNo = val
      this.topicList()
    },
    //课程选择
    handleSelectionChange(selection, val) {
      this.choiceTable = selection
      const arr = []
      const remainList = JSON.parse(JSON.stringify(this.selectList[this.params.type]))
      for (const i in this.selectList[this.params.type]) {
        if (val.id == this.selectList[this.params.type][i].id) {
          arr.push([i])
        }
      }
      if (arr.length == 1) {
        remainList.splice(parseInt(arr[0]), 1)
        this.selectList[this.params.type] = remainList
      } else {
        this.selectList[this.params.type] = [
          ...this.selectList[this.params.type],
          ...[this.choiceTable[selection.length - 1]]
        ]
      }
    },
    //删除选中的商品
    deleteCourse(index) {
      this.choiceCourseList[this.params.type].splice(index, 1)
    },
    //确认选中的商品
    confirmCourse() {
      this.showDialog = false
      this.filterParams.pageNo = 1
      this.choiceCourseList[this.params.type] = this.selectList[this.params.type]
      this.params.commodities = []
      this.params.commodities = this.choiceCourseList[this.params.type].map(e => {
        return e.id
      })
    },
    handTypeChange() {
      // console.log(1)
      this.params.commodities = this.choiceCourseList[this.params.type].map(e => {
        return e.id
      })
    },
    //表格选中的
    toggleSelection() {
      if (this.choiceCourseList[this.params.type].length > 0) {
        this.choiceCourseList[this.params.type].forEach((row, needIndex) => {
          this.courseList.forEach((list, index) => {
            if (list.id == row.id) {
              this.$refs.multipleTable.toggleRowSelection(
                this.courseList[index],
                true
              )
              this.choiceCourseList[this.params.type][
                needIndex
              ].pageNum = this.filterParams.pageNo
            }
          })
        })
      }
    },
    //全选
    choiceAll(selection) {
      var currentPageList = []
      const deleteList = JSON.parse(JSON.stringify(this.selectList[this.params.type]))
      for (const i in this.selectList[this.params.type]) {
        if (this.selectList[i].pageNum == this.filterParams.pageNo) {
          currentPageList.push(this.selectList[this.params.type][i])
        }
      }
      //取消全选
      if (selection.length < currentPageList.length) {
        currentPageList.forEach(row => {
          deleteList.forEach((lesson, index) => {
            if (lesson.id == row.id) {
              deleteList.splice(index, 1)
            }
          })
        })
        this.selectList[this.params.type] = deleteList
      } else {
        //全选
        const newAdd = JSON.parse(JSON.stringify(selection))
        this.selectList[this.params.type].forEach(row => {
          newAdd.forEach((lesson, index) => {
            if (lesson.id == row.id) {
              newAdd.splice(index, 1)
            }
          })
        })
        this.selectList[this.params.type] = [...this.selectList[this.params.type], ...newAdd]
      }
    },
    //操作
    operate() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.shadow == true) {
            this.addTopic()
          } else {
            this.amendTopic()
          }
        }
      })
    },
    //控制弹框显示问题
    isShow() {
      this.$emit('showDailog', false)
    },
    //新增
    addTopic() {
      addTopic(this.params).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.$message({
            message: '专题添加成功',
            type: 'success'
          })
          this.$router.push('/special/topicList')
        }
      })
    },
    //修改
    amendTopic() {
      const params = JSON.parse(JSON.stringify(this.params))
      delete params.createTime
      if (this.params.commodities[0].commodityName != undefined) {
        params.commodities = []
        for (const i in this.params.commodities) {
          params.commodities.push(this.params.commodities[i].id)
        }
      }
      topicAmend(params).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.$message({
            message: '专题修改成功',
            type: 'success'
          })
          this.$emit('showDailog', false)
          this.$emit('refresh', true)
        }
      })
    },
    //删除所有选中的商品
    deleteAllLesson() {
      // this.$set(this, "choiceCourseList", []);
      this.choiceCourseList[this.params.type] = []
      this.selectList[this.params.type] = []
      // this.$set(this, "selectList", []);
      this.$set(this.params, 'commodities', [])
      // this.params.commodities=[];
    }
  }
}
</script>

<style lang="scss">
.topic {
  .width {
    width: 300px;
  }
  .bigInput {
    width: 500px;
  }
  .inputWidth {
    width: 200px;
  }
  .imgBox {
    width: 330px;
    overflow: hidden;
    img {
      width: 100%;
    }
  }
  .unique {
    .el-form-item__content {
      margin-left: 0 !important;
      .el-upload__tip {
        margin-left: 112px;
      }
      .el-form-item__error {
        padding-left: 112px;
      }
      p{
        line-height: 10px;
      }
    }
  }
  .botttomBut {
    text-align: center;
    padding-top: 25px;
  }
  .filter {
    padding-bottom: 25px;
  }
  .pagination {
    padding-top: 15px;
  }
  .confirm {
    padding-left: 10px;
    color: #ccc;
    font-size: 12px;
  }
}

.tag_list {
  padding: 0;
  list-style: none;
  .tag_item {
    display: inline-block;
    background-color: rgba(144,147,153,.1);
    padding: 0 10px;
    height: 32px;
    line-height: 30px;
    font-size: 12px;
    color: #909399;
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(144,147,153,.2);
    text-align: center;
    margin-right:5px;
    .tag_close {
      border-radius: 50%;
      text-align: center;
      position: relative;
      cursor: pointer;

      top: -1px;
      right: -5px;
      color: #909399;
      font-style: normal;
      vertical-align: middle;
    }
    .tag_close:before {
      display: inline-block;
      content: 'x';
      height: 16px;
      width: 16px;
      font-size: 12px;

      line-height: 16px;
    }
    .tag_close:hover {
      background-color: #909399;
      color: #fff;
    }
  }
}

</style>
